<?php


namespace app;


use think\facade\Cache;

/**
 * 微信小程序配置
 */
class Package
{

    //**************************************************微信获取手机号******************************开始
    /**
     * Notes:获取手机号
     * User: gai
     * Date: 2022/6/27
     * Time: 9:59
     */
    public function getuserphonenumber($code){

        $access_token = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
        $params = [
            'code'=>$code
        ];
        $data = sendRequest($api,json_encode($params,320),'post');
        $res = json_decode($data['msg'], true);
        if($res['errcode']!=0){
            return $this->error('', $res['errmsg']);
        } else {
            return $this->success($res['phone_info']['phoneNumber']);
        }
    }

    /**
     * 获取微信接口的accessToken
     *
     * @param boolean $refresh 是否刷新accessToken
     * @param integer $expires accessToken缓存时间（秒）
     * @return string|null
     */
    public function getAccessToken($refresh = false, $expires = 3600)
    {
        $cacheKey = md5("{$this->appid}@access_token");

        $accessToken = Cache::get($cacheKey);
        $accessTokenOk = $this->checkAccessToken($accessToken);
        if (!$accessToken || $refresh || !$accessTokenOk) {
            $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $data = sendRequest($api,'','get');
            $res = json_decode($data['msg'], true);
            if (empty($res['access_token'])) {
                /*$this->errCode = isset($res['errcode']) ? $res['errcode'] : null;
                $this->errMsg = isset($res['errmsg']) ? $res['errmsg'] : null;
                return false;*/
                return $this->error('', $res['errmsg']);
            }
            $accessToken = $res['access_token'];
            Cache::set($cacheKey, $accessToken, $expires);
            return $accessToken;
        } else {
            return $accessToken;
        }
    }

    private function checkAccessToken($accessToken)
    {
        if (!$accessToken)
            return false;
        $api = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={$accessToken}";
        $data = sendRequest($api,'','get');
        $res = json_decode($data['msg'], true);
        if (!empty($res['errcode']) && $res['errcode'] != 1)
            return false;
        return true;
    }

    /**
     * Notes:微信openid
     * User: gai
     * Date: 2022/6/20
     * Time: 11:40
     */
    public function getOpenid($code){
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->appSecret}&js_code={$code}&grant_type=authorization_code";
        $data = sendRequest($api,'','get');
        $res = json_decode($data['msg'], true);
        return $res;
    }

    /**
     * Notes:小程序码
     * User: gai
     * Date: 2023/4/11
     * Time: 18:02
     */
    public function qrcode($scene,$page,$user_id){
        //$scence = "pid:{$this->auth->id}";
        //$page = input('page','pages/index/index/index');
        $request = Request::instance();
        $domain=$request->domain();
        $save_path = ROOT_PATH . 'public/qrcode/' . 'share_qrcode_' .$user_id. '.jpg';
        if (is_file( $save_path)){
            return  str_replace(ROOT_PATH.'public',$domain,$save_path);
        }

        $access_token = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $params = [
            'scene' => $scene,
            'page' => $page,
            'width' => 240,
        ];
        $data = sendRequest($api,json_encode($params),'post');

        //$msg = json_decode($data['msg']);

        $path = saveTempImageByContent($data['msg'],$save_path);

        //$res = json_decode($data['msg'], true);
        return  str_replace(ROOT_PATH.'public',$domain,$path);
    }

    //订阅消息
    public function sendmessage($openid,$page,$param_data,$template_id){
        $access_token = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
        $params = [
            'touser' => $openid,
            'template_id' => $template_id,
            'page' => $page,
            //'miniprogram_state' => 'developer',
            'data'=>$param_data
        ];

        $data = sendRequest($api,json_encode($params),'post');
        $msg = json_decode($data['msg']);

        if ($msg->errcode!=0) {
            //throw new \Exception($msg->errmsg);
            return  false;
        } else {
            return  true;
        }
    }

    public function sendRequest($url, $params = [], $method = 'POST', $options = [])
    {
        $method = strtoupper($method);
        $protocol = substr($url, 0, 5);
        $query_string = is_array($params) ? http_build_query($params) : $params;

        $ch = curl_init();
        $defaults = [];
        if ('GET' == $method) {
            $geturl = $query_string ? $url . (stripos($url, "?") !== false ? "&" : "?") . $query_string : $url;
            $defaults[CURLOPT_URL] = $geturl;
        } else {
            $defaults[CURLOPT_URL] = $url;
            if ($method == 'POST') {
                $defaults[CURLOPT_POST] = 1;
            } else {
                $defaults[CURLOPT_CUSTOMREQUEST] = $method;
            }
            $defaults[CURLOPT_POSTFIELDS] = $params;
        }

        $defaults[CURLOPT_HEADER] = false;
        $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
        $defaults[CURLOPT_FOLLOWLOCATION] = true;
        $defaults[CURLOPT_RETURNTRANSFER] = true;
        $defaults[CURLOPT_CONNECTTIMEOUT] = 3;
        $defaults[CURLOPT_TIMEOUT] = 3;

        // disable 100-continue
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        if ('https' == $protocol) {
            $defaults[CURLOPT_SSL_VERIFYPEER] = false;
            $defaults[CURLOPT_SSL_VERIFYHOST] = false;
        }

        curl_setopt_array($ch, (array)$options + $defaults);

        $ret = curl_exec($ch);
        $err = curl_error($ch);

        if (false === $ret || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            return [
                'ret'   => false,
                'errno' => $errno,
                'msg'   => $err,
                'info'  => $info,
            ];
        }
        curl_close($ch);
        return [
            'ret' => true,
            'msg' => $ret,
        ];
    }

    //**************************************************微信获取手机号******************************结束

    //*****************************************百度违禁词**********************************
    //获取token
    function getBaiduToken()
    {
        $AppID = '70933716';
        $API_Key = '5XxepGSOFjFEE3mRdoUZpR1l';
        $Secret_Key = 'g5EOBNTy17qdBpx4lRUaphVPFo5EzfW2';
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id=$API_Key&client_secret=$Secret_Key&grant_type=client_credentials",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',


            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response);
    }

    //请求是否有违禁词
    public function weijinci(){
        $token = getBaiduToken();

        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token->access_token;

        $bodys = array(
            'text' => '内容'
        );

        $detection_res = json_decode(request_post($url, $bodys));

        if ($detection_res->conclusionType!=1){
            $data['audit_status'] = 0;
        }
    }
    //**************************************************其他辅助方法******************************开始

    //保存图片内容到临时文件
    function saveTempImageByContent($content,$save_path)
    {
        $fp = fopen($save_path, 'w');
        fwrite($fp, $content);
        fclose($fp);
        return $save_path;
    }
    /**
     * 创建不重复的编号(抵抗高并发)
     * @param $prefix 前缀
     * @param $unique 唯一值
     */
    function createno($key, $prefix, $unique){

        $time_str = date('YmdHi');
        $max_no = \think\facade\Cache::get($key.$prefix.'_'.$unique . "_" . $time_str);
        if (!isset($max_no) || empty($max_no)) {
            $max_no = 1;
        } else {
            $max_no = $max_no + 1;
        }
        $no = $prefix.$time_str .$unique. sprintf("%04d", $max_no);
        \think\facade\Cache::set($key.$prefix.'_' .$unique. "_" . $time_str, $max_no);
        return $no;
    }

    /**
     * 获取近七日的时间
     * @param $time
     * @return array|boo
     */

    function getweeks($day = 10,$time = '', $format = 'Y-m-d')
    {
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i = 1; $i <= $day; $i++) {
            $date[ $i ] = date($format, strtotime('+' . $i - $day . ' days', $time));
        }
        return $date;
    }

    /**
     * 两个数字比
     * @param $first | $second
     * @return string
     */
    function diff_rate($first, $second)
    {
        if ($second != 0) {
            $result = sprintf('%.2f', ( ( $first - $second ) / $second ) * 100) . '%';
        } else if ($second == 0 & $first != 0) {
            $result = '100%';
        } else {
            $result = '0%';
        }
        return $result;
    }


    /**
     * 过滤特殊字符
     * @param $strParam
     * @return null|string|string[]
     */
    function replaceSpecialChar($strParam)
    {
        $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\（|\）|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\||\s+/";
        return preg_replace($regex, "", $strParam);
    }

    /**
     * 计算两个时间的间隔
     * @param $begin_time
     * @param $end_time
     * @return array
     */
    function timediff( $begin_time, $end_time )
    {
        if ( $begin_time < $end_time ) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime - $starttime;
        $days = intval( $timediff / 86400 );
        $remain = $timediff % 86400;
        $hours = intval( $remain / 3600 );
        $remain = $remain % 3600;
        $mins = intval( $remain / 60 );
        $secs = $remain % 60;

        $diff_str = '';
        if($days > 0){
            $diff_str .= $days.'天';
        }
        if($hours > 0){
            $diff_str .= $hours.'时';
        }
        if($mins > 0){
            $diff_str .= $mins.'分';
        }
        if($secs > 0){
            $diff_str .= $secs.'秒';
        }
        return $diff_str;
    }


    /**
     * 根据两点间的经纬度计算距离
     * @param float $lng1
     * @param float $lat1
     * @param float $lng2
     * @param float $lat2
     * @return number
     */
    function getDistance(float $lng1, float $lat1, float $lng2, float $lat2)
    {
        if (($lng1 == $lng2) && ($lat1 == $lat2)) {
            return 0;
        }
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    /**
     * 是否是url链接
     * @param $string
     * @return bool
     */
    function is_url($string)
    {
        if (strstr($string, 'http://') === false && strstr($string, 'https://') === false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 以天为单位 计算间隔内的日期数组
     * @param $srart_time
     * @param $end_time
     * @return array
     */
    function periodGroup($srart_time, $end_time, $format = 'Ymd')
    {
        $type_time = 3600 * 24;
        $data = [];
        for ($i = $srart_time; $i <= $end_time; $i += $type_time) {
            $data[] = date($format, $i);
        }
        return $data;
    }
}